<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>看点资讯</title>
    <script src="./vue.min.js"></script>
    <script src="./vuex.min.js"></script>
    <script src="./vue-router.min.js"></script>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 引入组件库 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="./axios.min.js"></script>
</head>

<body>
    <div id="app">
        <!-- 登录表单 -->
        <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="用户名">
                <el-input v-model="loginData.username" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item label="密码">
                <el-input v-model="loginData.password" placeholder="请输入密码"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button v-if="!token" type="primary" @click="login">登录</el-button>
                <el-button v-if="token" type="danger" @click="logout">退出</el-button>
            </el-form-item>
        </el-form>
        <!-- 路由匹配到的组件渲染到这里 -->
        <router-view></router-view>
    </div>
</body>
<script>
    // 实例化vuex
    var store = new Vuex.Store({
        state: {
            // 状态机
            categories: [],
        },
        mutations: {
            // 同步函数
            SET_CATEGOTY(state, payload) {
                state.categories = payload
            }
        },
        actions: {
            // 异步函数
            async findAllCategoies({ commit }) {
                axios({
                    baseURL: 'http://47.94.46.113:7788',
                    url: '/baseUser/findAll',
                    method: 'get',
                    headers: {
                        'Authorization': sessionStorage.getItem('token')
                    }
                }).then(res => {
                    commit('SET_CATEGOTY', res.data.data)
                }).catch(error => {
                    console.log(error);
                })
            }
        }
    })
    // 自定义组件
    let login = {
        template: `<div style="height:300px;
            background-color:lightblue;text-align:center;line-height:300px;font-size:40px">欢迎你，先登录吧！<div>`
    };
    let index = {
        template: `
        <div>
            <el-table :data="categories" style="width: 100%">
                <el-table-column prop="username" label="用户名" width="100"></el-table-column>
                <el-table-column prop="realname" label="姓名" width="100"></el-table-column>
                <el-table-column prop="telephone" label="手机号" width="100"></el-table-column>
                <el-table-column prop="gender" label="性别" width="100"></el-table-column>
                <el-table-column label="出生日期">
                    <template v-slot="scope">
                        {{ scope.row.birth | fmtDate}}
                    </template>
                </el-table-column>
                <el-table-column label="头像" width="200">
                    <template v-slot="scope">
                        <img :src="scope.row.userFace" width='200'>
                    </template>
                </el-table-column>
            </el-table>
        </div>`,
        computed: {
            ...Vuex.mapState(['categories'])
        },
        methods: {
            ...Vuex.mapActions(['findAllCategoies'])
        },
        created() {
            this.findAllCategoies()
        },
        // 过滤器
        filters: {
            fmtDate(val) {
                return new Date(val).toLocaleString();
            }
        }
    };
    // 实例化vue-router
    let router = new VueRouter({
        routes: [
            { path: '/', redirect: '/login' },
            { path: '/login', component: login },
            {
                path: '/index',
                component: index,
                beforeEnter(to, form, next) {
                    const token = sessionStorage.getItem('token')
                    if (token) {
                        next();
                    } else {
                        // this.$message.warning('请先登录！')
                        alert('请先登录！')
                        next('/login');
                    }
                }
            },
        ]
    });
    // 实例化Vue实例对象
    let vm = new Vue({
        el: '#app',
        data: {
            loginData: {
                username: '',
                password: ''
            },
            token: null
        },
        computed: {
            isLogin() {
                return sessionStorage.getItem('token');
            }
        },
        methods: {
            login() {
                axios({
                    baseURL: 'http://47.94.46.113:7788',
                    url: '/user/login',
                    method: 'post',
                    data: this.loginData
                }).then(res => {
                    // 将登录成功后返回的token存储到会话存储
                    sessionStorage.setItem('token', res.data.data.token)
                    this.token = sessionStorage.getItem('token')
                    // 登录成功之后进行跳转
                    this.$router.push({ path: '/index' })
                }).catch(error => {
                    console.log(error);
                })
            },
            logout() {
                // 清空存储的token
                sessionStorage.removeItem('token');
                this.token = null
                // 跳转至登录页
                this.$router.push('/login');
            }
        },
        router,  // 注入vue-router
        store,    // 注入vuex

    })
</script>

</html>